package com.itheima.controller;

import com.itheima.domain.Option;
import com.itheima.domain.Pow;
import com.itheima.domain.Student;
import com.itheima.domain.User;
import com.itheima.util.AgeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;

/*
    客服类:
        1. 接收用户请求
        2. 指挥业务员处理对应业务
        3. 将处理的结果响应给用户展示
 */
public class StudentController {
    private static final Logger LOGGER = LoggerFactory.getLogger(StudentController.class);
    public Scanner sc = new Scanner(System.in);

    private static User adminuser;

    public StudentController(User adminuser) {
        this.adminuser = adminuser;
    }


    // 客服的功能入口
    public final void start() throws Exception {
        while (true) {
            //1. 展示二级菜单列表
            System.out.println("********欢迎来到学生管理系统********");

            System.out.println("1. 添加学生" + (adminuser.getPow().compareTo(Pow.STUDENT) == 0 ? "  (锁定!)" : ""));
            System.out.println("2. 删除学生" + (adminuser.getPow().compareTo(Pow.STUDENT) == 0 ? "  (锁定!)" : ""));
            System.out.println("3. 修改学生" + (adminuser.getPow().compareTo(Pow.STUDENT) == 0 ? "  (锁定!)" : ""));


            System.out.println("4. 查看学生");
            System.out.println("5. 退出");

            //2. 用户录入选项,匹配对应功能
            String option = sc.next();

            //if (adminuser.getPow().compareTo(Pow.STUDENT) < 0){
            if (adminuser.getPow().compareTo(Pow.STUDENT) == 0) {
                if (!option.equals("4") && !option.equals("5")) {
                    System.out.println("权限不足,无法执行此操作");
                    continue;
                }
            }
            //}
            //3. 基于switch来进行菜单功能路由
            switch (option) {
                case "1":
                    addStudent();
                    break;
                case "2":
//                    System.out.println("删除学生功能自己实现...");
                    delectStudent();
                    break;
                case "3":
                    //System.out.println("修改学生功能自己实现...");
                    updateStudent();
                    break;
                case "4":
                    findAllStudent();
                    break;
                case "5":
                    System.out.println("感谢使用学生管理系统,再见!");
                    return;  // return 结束的当前方法!
                default:
                    System.out.println("输入有误!");
                    break;
            }
        }
    }

    private void updateStudent() throws IOException {
        //1. 采集用户信息-- 拿到要添加的学生信息
        System.out.println("请输入要修改的学号:");
        String id = sc.next();
        System.out.println("请输入新的姓名:");
        String name = sc.next();
        System.out.println("请输入新的生日:");
        String birthday = sc.next();
        //通过工具类,自动计算年龄
        String age = AgeUtil.getAge(birthday);
        //封装成学生对象
        Student stu = new Student(id, name, age, birthday);
        //调用方法,将其传入服务器,并接受返回数据
        LOGGER.info("执行添加学生,发送信息为: " + Option.UPDATE_STUDENT + "&" + stu.toString());
        System.out.println(sendMsgToServer(Option.UPDATE_STUDENT + "&" + stu.toString()));
    }

    //客户端删除功能
    private void delectStudent() throws Exception {
        //采集数据

        System.out.println("请输入要删除的学生学号: ");
        String id = sc.next();
        String clientMsg = Option.DELECT_STUDENT + "&" + id;
        LOGGER.info("执行删除学生,发送请求为:" + clientMsg);
        System.out.println(sendMsgToServer(clientMsg));
        //findAllStudent();
/*//发送请求给服务器,进行业务操作
        Socket socket = getSocket();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(clientMsg);
        bw.newLine();
        bw.flush();
        socket.shutdownOutput();

        //接收服务器返回数据,并展示给用户
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String resultInfo = br.readLine();
        bw.close();
        socket.close();
        System.out.println(resultInfo);*/

    }

    //发送请求给服务器,返回服务器传回结果
    private Object sendMsgToServer(String clientMsg) throws IOException {
        LOGGER.info("发送请求:" + clientMsg + "给服务器");
        //发送请求给服务器,进行业务操作
        Socket socket = getSocket();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(clientMsg);
        bw.newLine();
        bw.flush();
        socket.shutdownOutput();

        //接收服务器返回数据,并展示给用户
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String resultInfo = br.readLine();
        bw.close();
        socket.close();
        LOGGER.info("服务器响应回数据:" + clientMsg);
        return resultInfo;
    }

    //客户端查看功能
    private void findAllStudent() throws Exception {
        //List<Student> list = (List<Student>) sendMsgToServer(Option.FINDALL_STUDENT + "&Student");
        //1. 请求服务器,获取列表数据
        LOGGER.info("执行查看学生,发送请求为:" + Option.FINDALL_STUDENT + "&itheima");
        Socket socket = getSocket();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(Option.FINDALL_STUDENT + "&itheima");
        bw.newLine();
        bw.flush();
        socket.shutdownOutput();

        //2. 接收服务器响应回来的结果
        InputStream is = socket.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(is);
        List<Student> list = (List<Student>) ois.readObject();
        ois.close();
        socket.close();
        LOGGER.info("执行查看学生,接收响应为:" + list);

        //3. 判断系统有没有数据
        if (list == null || list.size() == 0) {
            System.out.println("系统暂无数据,请添加后重试!");
        } else {
            System.out.println("学号\t\t姓名\t年龄\t生日");
            list.forEach(stu -> System.out.println(stu.getId() + "\t" + stu.getName() + "\t" + stu.getAge() + "\t\t" + stu.getBirthday()));
        }

    }


    //客户端添加功能
    private void addStudent() throws Exception {
        //1. 采集用户信息-- 拿到要添加的学生信息
        System.out.println("请输入学号:");
        String id = sc.next();
        System.out.println("请输入姓名:");
        String name = sc.next();
        System.out.println("请输入生日:");
        String birthday = sc.next();
        //通过工具类,自动计算年龄
        String age = AgeUtil.getAge(birthday);

        //2. 封装学生对象
        Student stu = new Student(id, name, age, birthday);

        String clientMsg = Option.ADD_STUDENT + "&" + stu.toString();
        System.out.println(sendMsgToServer(clientMsg));

        // findAllStudent();
        /*//3. 发送请求给服务器,进行添加业务处理
        //注意: 自己设计传输报文: 1&heima001,柳岩,36,1999-11-11
        Socket socket = getSocket();

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(clientMsg);
        bw.newLine();
        bw.flush();


        //4. 接收服务器响应回来的结果数据,展示给用户
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String resultInfo = br.readLine();
        System.out.println(resultInfo);

        socket.close();*/
    }

    //封装一个方法,专门获取socket对象
    private Socket getSocket() {
        try {
            return new Socket("127.0.0.1", 10086);
        } catch (Exception e) {
            return null;
        }
    }

}
